//
//  GKZYUserRegisterViewController.m
//  GKZYAid
//
//  Created by lanou3g on 16/3/14.
//  Copyright © 2016年 GKZYAid. All rights reserved.
//

#import "GKZYUserRegisterViewController.h"

#define LTVIEW_X ((self.view.frame.size.width) * 0.13)
#define LTVIEW_WIDTH ((self.view.frame.size.width) * 0.7)
#define LTVIEW_HEIGHT ((self.view.frame.size.height) * 0.05)
#define GAP ((self.view.frame.size.height)  * 0.03)
#define NUM 101

@interface GKZYUserRegisterViewController ()

@end

@implementation GKZYUserRegisterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self addAllViews];
    
    [self setDelegate];
}
- (void)addAllViews
{
    self.title = @"用户注册";
    self.imageView.backgroundColor = [UIColor whiteColor];
    
    self.imageView = [[UIImageView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.imageView.userInteractionEnabled = YES;
    self.imageView.image = [UIImage imageNamed:@"background"];
    self.imageView.alpha = 0.8;
    [self.view addSubview:self.imageView];
    
    UIBarButtonItem *leftBarButton = [[UIBarButtonItem alloc] initWithTitle:@"登陆" style:UIBarButtonItemStylePlain target:self action:@selector(leftBarButtonAction:)];
    self.navigationItem.leftBarButtonItem = leftBarButton;
    
    UIBarButtonItem *rightBarButton = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(rightBarButtonAciton:)];
    self.navigationItem.rightBarButtonItem = rightBarButton;
    
    self.userName = [[LabelTextFieldView alloc] initWithFrame:CGRectMake(LTVIEW_X, self.imageView.frame.size.height  * 0.08 + 44, LTVIEW_WIDTH, LTVIEW_HEIGHT)];
    [self.imageView addSubview:self.userName];
    [self.userName setLabelText:@"用户名:" textFieldPlaceholder:@"请输入用户名" isCiphertext:NO textFieldTag:(self.userName.frame.origin.y + NUM)];
    
    self.labelUserName = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(self.userName.frame), self.userName.frame.origin.y, self.imageView.frame.size.width * 0.1, self.userName.frame.size.height)];
    self.labelUserName.text = @"*";
    self.labelUserName.textAlignment = NSTextAlignmentCenter;
    self.labelUserName.textColor = [UIColor redColor];
    [self.imageView addSubview:self.labelUserName];
    
    self.userPassword = [[LabelTextFieldView alloc] initWithFrame:CGRectMake(LTVIEW_X, CGRectGetMaxY(self.userName.frame) + GAP, LTVIEW_WIDTH, LTVIEW_HEIGHT)];
    [self.imageView addSubview:self.userPassword];
    [self.userPassword setLabelText:@"密码:" textFieldPlaceholder:@"请输入密码" isCiphertext:YES textFieldTag:(self.userPassword.frame.origin.y + NUM)];
    
    self.labelPassword = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(self.userPassword.frame), self.userPassword.frame.origin.y, self.imageView.frame.size.width * 0.1, self.userPassword.frame.size.height)];
    self.labelPassword.text = @"*";
    self.labelPassword.textAlignment = NSTextAlignmentCenter;
    self.labelPassword.textColor = [UIColor redColor];
    [self.imageView addSubview:self.labelPassword];
    
    self.userPasswordSure = [[LabelTextFieldView alloc] initWithFrame:CGRectMake(LTVIEW_X, CGRectGetMaxY(self.userPassword.frame) + GAP, LTVIEW_WIDTH, LTVIEW_HEIGHT)];
    [self.imageView addSubview:self.userPasswordSure];
    [self.userPasswordSure setLabelText:@"密码确认:" textFieldPlaceholder:@"请再次输入密码" isCiphertext:YES textFieldTag:(self.userPasswordSure.frame.origin.y + NUM)];
    
    self.labelPasswordSure = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(self.userPasswordSure.frame), self.userPasswordSure.frame.origin.y, self.imageView.frame.size.width * 0.1, self.userPasswordSure.frame.size.height)];
    self.labelPasswordSure.text = @"*";
    self.labelPasswordSure.textAlignment = NSTextAlignmentCenter;
    self.labelPasswordSure.textColor = [UIColor redColor];
    [self.imageView addSubview:self.labelPasswordSure];
    
    self.userMail = [[LabelTextFieldView alloc] initWithFrame:CGRectMake(LTVIEW_X, CGRectGetMaxY(self.userPasswordSure.frame) + GAP, LTVIEW_WIDTH, LTVIEW_HEIGHT)];
    [self.imageView addSubview:self.userMail];
    [self.userMail setLabelText:@"邮箱:" textFieldPlaceholder:@"请输入有效邮箱" isCiphertext:NO textFieldTag:(self.userMail.frame.origin.y + NUM)];
    
    self.labelMail = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(self.userMail.frame), self.userMail.frame.origin.y, self.imageView.frame.size.width * 0.1, self.userMail.frame.size.height)];
    self.labelMail.text = @"*";
    self.labelMail.textAlignment = NSTextAlignmentCenter;
    self.labelMail.textColor = [UIColor redColor];
    [self.imageView addSubview:self.labelMail];
    
    self.buttonSure = [UIButton buttonWithType:UIButtonTypeCustom];
    self.buttonSure.frame = CGRectMake(LTVIEW_X, CGRectGetMaxY(self.userMail.frame) + GAP, LTVIEW_WIDTH, LTVIEW_HEIGHT * 1.3);
    [self.buttonSure setTitle:@"注册" forState:UIControlStateNormal];
    self.buttonSure.backgroundColor = [UIColor orangeColor];
    [self.imageView addSubview:self.buttonSure];
    [self.buttonSure addTarget:self action:@selector(buttonSureAction:) forControlEvents:UIControlEventTouchUpInside];
    
    self.labelHint = [[UILabel alloc] initWithFrame:CGRectMake(LTVIEW_X, CGRectGetMaxY(self.buttonSure.frame) + GAP, LTVIEW_WIDTH, LTVIEW_HEIGHT * 2)];
    self.labelHint.text = @"*注:请将do-not-reply@apps.leancloud.cn\n添加到邮箱白名单中";
    self.labelHint.textColor = [UIColor redColor];
    self.labelHint.textAlignment = NSTextAlignmentCenter;
    self.labelHint.font = [UIFont systemFontOfSize:15.0];
    self.labelHint.numberOfLines = 0;
    [self.view addSubview:self.labelHint];
}

- (void)setDelegate
{
    self.userName.LTTextField.delegate = self;
    self.userPassword.LTTextField.delegate = self;
    self.userPasswordSure.LTTextField.delegate = self;
    self.userMail.LTTextField.delegate = self;
}

- (void)textFieldResignFirstRespoder
{
    [self.userName.LTTextField resignFirstResponder];
    [self.userPassword.LTTextField resignFirstResponder];
    [self.userPasswordSure.LTTextField resignFirstResponder];
    [self.userMail.LTTextField resignFirstResponder];
}

//键盘回收
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.userName.LTTextField resignFirstResponder];
    [self.userPassword.LTTextField resignFirstResponder];
    [self.userPasswordSure.LTTextField resignFirstResponder];
    [self.userMail.LTTextField resignFirstResponder];
}

- (void)rightBarButtonAciton:(UIBarButtonItem *)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

//登陆按钮事件
- (void)leftBarButtonAction:(UIBarButtonItem *)sender
{
    GKZYUserLoginViewController *loginVC = [[GKZYUserLoginViewController alloc] init];
    [self.navigationController pushViewController:loginVC animated:YES];
}

- (void)buttonSureAction:(UIButton *)sender
{
    [self textFieldResignFirstRespoder];
    [self getUserMessage];
    if (self.strUserName.length) {
        if ([self.strUserPassword isEqualToString:self.strUserPasswordSure]) {
            [self addSureMessageAlertContrller];
        }else{
            [self addPasswordDifferentErrorAlertController];
        }
    }else{
        [self addUserNameIsNilErrorAlertController];
    }
}

- (void)getUserMessage
{
    self.strUserName = self.userName.LTTextField.text;
    self.strUserPassword = self.userPassword.LTTextField.text;
    self.strUserPasswordSure = self.userPasswordSure.LTTextField.text;
    self.strUserMail = self.userMail.LTTextField.text;
}

- (void)addSureMessageAlertContrller
{
    NSString *userMessage = [NSString stringWithFormat:@"用户名:%@\n邮箱:%@",self.strUserName,self.strUserMail];
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"信息确认" message:userMessage preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *alertActionSure = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self saveUser];
    }];
    UIAlertAction *alertActionCancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
#warning ----- Cancel check message will skip to LoginView 取消确认信息,跳转到登陆页面
        [self textFieldEmptySet];
        GKZYUserLoginViewController *loginVC = [[GKZYUserLoginViewController alloc] init];
        [self.navigationController pushViewController:loginVC animated:YES];
    }];
    [alertController addAction:alertActionSure];
    [alertController addAction:alertActionCancel];
    [self presentViewController:alertController animated:YES completion:nil];
}

- (void)textFieldEmptySet
{
    self.userName.LTTextField.text = nil;
    self.userPassword.LTTextField.text = nil;
    self.userPasswordSure.LTTextField.text = nil;
}

- (void)saveUser
{
    AVUser *user = [AVUser user];
    user.username = self.strUserName;
    user.password = self.strUserPassword;
    user.email = self.strUserMail;
    [user signUpInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
        if (succeeded) {
            [self addRegisterSucceedAlertController];
        }else{
            NSLog(@"%@",error);
            if (error.code == 202) {
                [self addUserNameIsExistsErrorAlertController];
            }else if (error.code == 205) {
                [self addUserMailIsWrongAlertController];
            }else if (error.code == 125){
                [self addUserMailIsWrongAlertController];
            }else{
                [self addUserRegisterFail];
            }
        }
    }];
}

- (void)addRegisterSucceedAlertController
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"注册成功" message:@"" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *alertAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
#warning ----- RegisteSucceed will skip to LoginView 注册成功,跳转到登陆页面
        GKZYUserLoginViewController *loginVC = [[GKZYUserLoginViewController alloc] init];
        loginVC.loginUserName = self.strUserName;
#warning Insert userName into table "UserInformation"(注册成功后向UserInformation表中插入用户名和默认头像)
        AVObject *objectUser = [AVObject objectWithClassName:@"UserInformation"];
        [objectUser setObject:self.strUserName forKey:@"userName"];
        UIImage *userIcon = [UIImage imageNamed:@"UserCenter_HeadPortrait"];
        NSData *dataIcon = UIImagePNGRepresentation(userIcon);
        AVFile *fileUserIcon = [AVFile fileWithData:dataIcon];
        [objectUser setObject:fileUserIcon forKey:@"userImage"];
        [objectUser saveInBackground];
        [self.navigationController pushViewController:loginVC animated:YES];
    }];
    [alertController addAction:alertAction];
    [self presentViewController:alertController animated:YES completion:nil];
}

- (void)addUserNameIsExistsErrorAlertController
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"用户名已存在" message:@"" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *alertAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        self.userName.LTTextField.text = nil;
        self.userPassword.LTTextField.text = nil;
        self.userPasswordSure.LTTextField.text = nil;
        self.userMail.LTTextField.text = nil;
    }];
    [alertController addAction:alertAction];
    [self presentViewController:alertController animated:YES completion:nil];
}

- (void)addUserMailIsWrongAlertController
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"邮箱地址无效" message:@"" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *alertAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        self.userName.LTTextField.text = nil;
        self.userPassword.LTTextField.text = nil;
        self.userPasswordSure.LTTextField.text = nil;
        self.userMail.LTTextField.text = nil;
    }];
    [alertController addAction:alertAction];
    [self presentViewController:alertController animated:YES completion:nil];
}

- (void)addPasswordDifferentErrorAlertController
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"两次密码输入不一致" message:@"" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *alertAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        self.userName.LTTextField.text = nil;
        self.userPassword.LTTextField.text = nil;
        self.userPasswordSure.LTTextField.text = nil;
        self.userMail.LTTextField.text = nil;
    }];
    [alertController addAction:alertAction];
    [self presentViewController:alertController animated:YES completion:nil];
}

- (void)addUserNameIsNilErrorAlertController
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"用户名不能为空" message:@"" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *alertAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
    }];
    [alertController addAction:alertAction];
    [self presentViewController:alertController animated:YES completion:nil];
}

- (void)addUserRegisterFail
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"注册失败" message:@"" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *alertAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        self.userName.LTTextField.text = nil;
        self.userPassword.LTTextField.text = nil;
        self.userPasswordSure.LTTextField.text = nil;
        self.userMail.LTTextField.text = nil;
    }];
    [alertController addAction:alertAction];
    [self presentViewController:alertController animated:YES completion:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
